let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let const_js = require("../../utils/const.js");
let cart_js = require("../../utils/cart.js");
let sys_js = require("../../utils/system.js");
let user_js = require("../../utils/user.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');
let api = require("../../utils/apiRequest.js");

Page({
  data: {
    sysInfo: null,
    userInfo: null,
    pageScrollTop: 0,
    containerTouchmove: '',
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    loginStatus: -1, //0 未登录 1已登录
    contentStatus: -1, //1有数据
    noLoginUrl: url_js.imgUrl + "unlogin.png",
    noGoodsUrl: url_js.imgUrl + "no_goods.png",
    cartList: null,
    pageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    faviroteList: [],
    selectedCartInfo: {
      count: 0,
      price: 0.0,
      isSelctedAll: false
    }
  },

  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.注册通知
    this.registNotification();
    //3.初始化数据
    this.initData(options);
    //4.获取购物车数据
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //4.获取购物车数据
    if (this.data.loginStatus == 1) {
      //reset Data 
      this.resetSelectedCartInfo();
      //relaod data
      if (this.data.faviroteList.length == 0) {
        this.requestToGetCartList(true, true, this.data.pageInfo, true);
        return
      }
      this.requestToGetCartList(true, false, this.data.pageInfo, true);
    }
  },

  //初始化数据
  initData: function (options) {
    //userInfo
    let tempUserInfo = user_js.userInfo();
    let tmpLoginSt = (user_js.isLogin() ? 1 : 0);
    this.setData({
      userInfo: tempUserInfo,
      loginStatus: tmpLoginSt,
      sysInfo: sys_js.systemInfo()
    })
  },

  //注册通知，当自提点切换的时候，更新数据
  registNotification: function () {
    let that = this;
    notificationCenter.addNotification(const_js.changeShopSucessNoti, that.changedShop, that);
    notificationCenter.addNotification(const_js.loginSucessNoti, that.bLoginCustomer, that);
  },

  //自提点切换
  changedShop: function () {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo
    });
    //2.刷新数据
    this.resetPageInfo();
    this.requestToGetCartList(true, true, this.data.pageInfo, true);
  },

  //重置pageInfo 
  resetPageInfo: function () {
    let tmpPageInfo = this.data.pageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      pageInfo: tmpPageInfo
    });
  },

  //重置计算信息
  resetSelectedCartInfo: function () {
    let tmpCartInfo = this.data.selectedCartInfo;
    tmpCartInfo.count = 0;
    tmpCartInfo.price = 0;
    tmpCartInfo.isSelctedAll = false;
    this.setData({
      selectedCartInfo: tmpCartInfo
    });
  },

  //从未登录状态到登录状态
  bLoginCustomer: function () {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo,
      loginStatus: (user_js.isLogin() ? 1 : 0)
    });
    //2.刷新数据
    this.resetPageInfo();
    this.requestToGetCartList(true, true, this.data.pageInfo, true);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //移除通知
    let that = this;
    notificationCenter.removeNotification(const_js.changeShopSucessNoti, that);
    notificationCenter.removeNotification(const_js.loginSucessNoti, that);
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //获取购物车列表isGoods刷新大家都在买
  requestToGetCartList: function (isCart, isGoods, goodPageInfo, pullDownRefresh) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      shopId: this.data.userInfo.ztd.id
    }
    //
    let faviData = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      curPage: goodPageInfo.curPage,
      pageSize: goodPageInfo.pageSize,
      shopId: this.data.userInfo.ztd.id
    }
    let requestList = [];
    if (isCart) {
      requestList.push(api.wxRequest(url_js.cartListUrl, data));
    }
    if (isGoods) {
      requestList.push(api.wxRequest(url_js.recommendRecommendUrl, faviData));
    }
    Promise.all(requestList).then(results => {
      if (isCart) {
        this.handleCartListData(results[0], pullDownRefresh);
      }
      if (isGoods) {
        let resData = isCart ? results[1] : results[0];
        this.handleRecommendRecommendData(resData, goodPageInfo, pullDownRefresh);
      }
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理返回的购物车数据
  handleCartListData: function (res, pullDownRefresh) {
    //设置数据
    let tmpList = this.data.cartList;
    if (pullDownRefresh) {
      tmpList = [];
    }
    //list
    if (res.result.length > 0) {
      tmpList = res.result;
    } else {
      tmpList = [];
    }

    //更新购物车信息
    cart_js.updateCartWithSkuList(tmpList);

    this.setData({
      cartList: tmpList
    });

    // reset
    if (pullDownRefresh) {
      this.resetSelectedCartInfo();
    }
  },

  //处理大家都在买的数据
  handleRecommendRecommendData: function (res, goodPageInfo, pullDownRefresh) {
    //设置数据
    let tmpList = this.data.faviroteList;
    if (pullDownRefresh) {
      tmpList = [];
    }
    //pageInfo
    let tmpPageInfo = this.data.pageInfo;
    if (res.page.pages <= goodPageInfo.curPage) {
      tmpPageInfo.noMore = true;
    } else {
      tmpPageInfo.curPage++;
    }
    //list
    if (res.result.length > 0) {
      tmpList = tmpList.concat(res.result);
      this.setData({
        pageInfo: tmpPageInfo,
        faviroteList: tmpList
      });
    } else {
      this.setData({
        pageInfo: tmpPageInfo
      });
    }
  },


  //增加购物车
  //cartIndex购物车内添加商品
  requestToAddCart: function (skuItem, productId, skuId, num, cartIndex) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num, cartIndex);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num, cartIndex) {
    cart_js.addCart(skuItem, skuId, num);
    if (cartIndex >= 0) {
      let tmpList = this.data.cartList;
      let item = tmpList[cartIndex];
      item.num++;
      tmpList.splice(cartIndex, 1, item);


      //刷新购物车数量，合计金额
      if (skuItem.selected) {
        let tmpSelectedCartInfo = cart_js.selectedCarInfoWithSkuList(tmpList);
        this.setData({
          selectedCartInfo: tmpSelectedCartInfo,
          cartList: tmpList
        });
      } else {
        this.setData({
          cartList: tmpList
        });
      }

    } else {
      common_js.showToast("添加购物车成功");
      //刷新购物车
      this.requestToGetCartList(true, false, this.data.pageInfo, true);
    }
  },

  //删除购物车商品
  requestToDeleteCart: function (num, skuId, cartIndex) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId,
      num: num
    };
    api.wxRequest(url_js.cartDeleteUrl, data).then(res => {
      this.handleDeleteCartData(res, skuId, num, cartIndex);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleDeleteCartData: function (res, skuId, num, cartIndex) {
    cart_js.minusCart(skuId, num);

    if (cartIndex >= 0) {
      let tmpList = this.data.cartList;
      let item = tmpList[cartIndex];
      item.num = item.num - num;
      if (item.num == 0) {
        tmpList.splice(cartIndex, 1);
      } else {
        tmpList.splice(cartIndex, 1, item);
      }
      //刷新购物车数量，合计金额
      if (item.selected) {
        let tmpSelectedCartInfo = cart_js.selectedCarInfoWithSkuList(tmpList);
        this.setData({
          selectedCartInfo: tmpSelectedCartInfo,
          cartList: tmpList
        });
      } else {
        this.setData({
          cartList: tmpList
        });
      }
    }
  },

  //去登录
  gotoLogin: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cardLogin);

    wx.navigateTo({
      url: '../loginIndex/loginIndex'
    });
  },

  //去逛逛
  gotoBuy: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cardGg);

    wx.switchTab({
      url: '../category/category'
    });
  },

  //去结算
  gotoPay: function (e) {
    if (!this.data.cartList || this.data.cartList.length == 0) return;

    if (this.data.selectedCartInfo.count == 0) {
      common_js.showToast("请选择结算的商品");
      return
    }
    //如果购物车有万人团预购的商品提示
    let selectedCartlist = cart_js.selectedCartList(this.data.cartList);
    if (cart_js.hasPreBuyMillionGoods(selectedCartlist)) {
      common_js.showToast("万人团活动预热中，请持续关注，过会再来吧~");
      return;
    }

    let skuList = cart_js.paymentSkuList(this.data.cartList);
    wx.navigateTo({
      url: '../payment/payment?skuList=' + common_js.jsonStringify(skuList)
    });
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cardPay);
  },

  //全选
  onSelectAll: function (e) {
    if (!this.data.cartList || this.data.cartList.length == 0) return;

    //全部选中，全部非选
    let tmpSelectedCartInfo = this.data.selectedCartInfo;
    if (tmpSelectedCartInfo.isSelctedAll) {
      tmpSelectedCartInfo = cart_js.selectedCarInfoWithSkuList(this.data.cartList, 2);
    } else {
      tmpSelectedCartInfo = cart_js.selectedCarInfoWithSkuList(this.data.cartList, 1);
    }
    this.setData({
      selectedCartInfo: tmpSelectedCartInfo,
      cartList: tmpSelectedCartInfo.skuList
    });
  },

  //购物车商品列表点击
  onCartItem: function (e) {
    let index = e.currentTarget.dataset.index;
    let tmpList = this.data.cartList;
    let item = tmpList[index];
    //1.正常商品
    if (item.type == 0 && !item.checkFlag) {
      common_js.showToast(item.checkMessage);
      return;
    }
    //2.限购商品
    if (item.type != 0 && item.stockLeft < item.num && !item.checkFlag) {
      common_js.showToast(item.checkMessage);
      return;
    }

    if (item.selected) {
      item.selected = !item.selected;
    } else {
      item.selected = true;
    }

    tmpList.splice(index, 1, item);
    //计算当前购物车总数量和价格
    let tmpSelectedCartInfo = this.data.selectedCartInfo;
    tmpSelectedCartInfo = cart_js.selectedCarInfoWithSkuList(tmpList);

    this.setData({
      selectedCartInfo: tmpSelectedCartInfo,
      cartList: tmpList
    });
  },

  //购物车数量添加
  onCardItemAdd: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.cartList[index];
    //1.正常商品
    if (item.type == 0 && !item.checkFlag) {
      common_js.showToast(item.checkMessage);
      return;
    }

    //限时抢购单独判断
    if (item.type != 0) {
      let cartLimitCount = cart_js.limitSkuCountWithSkuId(item.skuId);
      let isAlert = (cartLimitCount == 0) ? (item.count > item.userBuyLimit) : (cartLimitCount >= item.userBuyLimit);
      if (isAlert) {
        common_js.showModal("每人限购" + item.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
          this.requestToAddCart(item, item.productId, item.skuId, 1, index);
        })
        return;
      }
    }
    this.requestToAddCart(item, item.productId, item.skuId, 1, index);
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cardListGoodsAdd);
  },

  //购物车数量减少
  onCardItemMinus: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.cartList[index];
    if (item.num - 1 == 0) {
      //提示
      common_js.showModal("确定删除商品？", null, true, null, "删除", () => {
        //移除商品
        this.requestToDeleteCart(1, item.skuId, index);
      })
    } else {
      this.requestToDeleteCart(1, item.skuId, index);
    }
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cardListGoodsMinus);
  },

  //商品失效，直接删除
  onCartDelete: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.cartList[index];
    //提示
    common_js.showModal("确定删除商品？", null, true, null, "删除", () => {
      //移除商品
      this.requestToDeleteCart(item.num, item.skuId, index);
    })
  },

  //查看登录状态，未登录直接跳转登录
  checkIsToLoginIndex: function () {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return false;
    }
    return true;
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  //添加商品
  onAddGoods: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let index = e.currentTarget.dataset.index;
    let item = this.data.faviroteList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cardDjdzmAdd);
  },

  //商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.faviroteList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.loginStatus != 1) {
      wx.stopPullDownRefresh();
      return
    }
    //request
    this.resetPageInfo();
    this.requestToGetCartList(true, true, this.data.pageInfo, true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    //购物车没有数据
    if (this.data.cartList.length == 0) return;
    if (this.data.pageInfo.noMore) return;
    this.requestToGetCartList(false, true, this.data.pageInfo);
  }
})